package com.swinw.asumall.product.web;

import com.swinw.asumall.product.entity.CategoryEntity;
import com.swinw.asumall.product.service.CategoryService;
import com.swinw.asumall.product.vo.Catalog2LaveVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Resource
    CategoryService categoryService;

    @Resource
    RedissonClient redisson;

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1、获取锁
        RLock lock = redisson.getLock("my_lock");
        //2、加锁
        lock.lock();

        /**
         * 锁默认有效时间30s
         * 2.1、所得自动续期，如果业务超长，在运行期间，会自动给锁续30秒有效时间
         *      所以不用担心业务时间长，锁自动过期被删掉
         * 2.2、加锁的业务只要运行完成，就不会给当前锁续期，即使不自动解锁，Redisson
         *      也会默认30s自动删除
         */
        try{
            //3、执行业务代码
            System.out.println("加锁成功，开始执行业务代码 ————>" + Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){

        }finally {
            System.out.println("释放锁 ————>" + Thread.currentThread().getId());
            lock.unlock();//解锁
        }
        return "haah";
    }

    /**
     * 当页面访问 / 或者 /index.html 都去index页面
     * 同时查询出一级分类
     * @return
     */
    @GetMapping({"/","/index.html"})
    public String index(Model model){
        List<CategoryEntity> categorys = categoryService.catelogLaveOne(0L);
        model.addAttribute("categorys",categorys);
        return "index";
    }

    @ResponseBody
    @RequestMapping("/index/catalog.json")
    public Map<String, List<Catalog2LaveVo>> getCatalog2Json(){
        return categoryService.getCatalogMap();
    }

}
